package com.edu.buaa;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";

    private EditText etUsername, etPassword;
    private Button btnLogin;
    private TextView tvRegister;
    private DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        Log.d(TAG, "onCreate: Activity started");

        // 检查是否已登录
//        if (isLoggedIn()) {
//            Log.d(TAG, "User already logged in, redirecting to BirthInputActivity");
//            startActivity(new Intent(LoginActivity.this, BirthInputActivity.class));
//            finish();
//            return;
//        }

        try {
            initViews();
            setupUnderlineText();
            databaseHelper = new DatabaseHelper(this);
            setupClickListeners();
            Log.d(TAG, "All components initialized successfully");
        } catch (Exception e) {
            Log.e(TAG, "Error during initialization: " + e.getMessage(), e);
            Toast.makeText(this, "初始化失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private void initViews() {
        Log.d(TAG, "Initializing views");
        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        btnLogin = findViewById(R.id.btnLogin);
        tvRegister = findViewById(R.id.tvRegister);

        // 检查视图是否成功初始化
        if (etUsername == null) Log.e(TAG, "etUsername is null");
        if (etPassword == null) Log.e(TAG, "etPassword is null");
        if (btnLogin == null) Log.e(TAG, "btnLogin is null");
        if (tvRegister == null) Log.e(TAG, "tvRegister is null");
    }

    private void setupUnderlineText() {
        try {
            SpannableString registerText = new SpannableString("还没有账号？立即注册");
            registerText.setSpan(new UnderlineSpan(), 0, registerText.length(), 0);
            tvRegister.setText(registerText);
            Log.d(TAG, "Underline text set successfully");
        } catch (Exception e) {
            Log.e(TAG, "Error setting underline text: " + e.getMessage(), e);
        }
    }

    private void setupClickListeners() {
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginUser();
            }
        });

        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "Register link clicked");
                try {
                    Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                    Log.d(TAG, "Intent created, starting activity");
                    startActivity(intent);
                    Log.d(TAG, "RegisterActivity started successfully");
                } catch (Exception e) {
                    Log.e(TAG, "Error starting RegisterActivity: " + e.getMessage(), e);
                    Toast.makeText(LoginActivity.this, "无法打开注册页面: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private void loginUser() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "请输入用户名和密码", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            if (databaseHelper.checkLogin(username, password)) {
                saveLoginStatus(username);
                Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(LoginActivity.this, BirthInputActivity.class));
                finish();
            } else {
                Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "Login error: " + e.getMessage(), e);
            Toast.makeText(this, "登录失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private void saveLoginStatus(String username) {
        try {
            SharedPreferences sharedPreferences = getSharedPreferences("user_prefs", MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("is_logged_in", true);
            editor.putString("username", username);
            editor.putInt("user_id", databaseHelper.getUserId(username));
            editor.apply();
            Log.d(TAG, "Login status saved for user: " + username);
        } catch (Exception e) {
            Log.e(TAG, "Error saving login status: " + e.getMessage(), e);
        }
    }

    private boolean isLoggedIn() {
        try {
            SharedPreferences sharedPreferences = getSharedPreferences("user_prefs", MODE_PRIVATE);
            return sharedPreferences.getBoolean("is_logged_in", false);
        } catch (Exception e) {
            Log.e(TAG, "Error checking login status: " + e.getMessage(), e);
            return false;
        }
    }

    // 在 LoginActivity 中添加
    @Override
    public void onBackPressed() {
        // 在登录页面按返回键退出应用
        new android.app.AlertDialog.Builder(this)
                .setTitle("退出应用")
                .setMessage("确定要退出紫微斗数排盘系统吗？")
                .setPositiveButton("确定", (dialog, which) -> finish())
                .setNegativeButton("取消", null)
                .show();
    }
}